<template>
	<view class="container">
		<view class="flex justify-between align-center text-15 text-333 padding-sm bg-white" style="
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        height: 68rpx;
        z-index: 1;
      ">
			<view class=""> 共{{ totalNum }}件商品 </view>
			<view class="" @click="editStatus(2)" v-if="status == 1"> 管理 </view>
			<view class="" @click="editStatus(1)" v-if="status == 2"> 完成 </view>
		</view>
		<view class="" style="height: 68rpx"> </view>
		<view class="margin padding text-15 text-333 bg-white radius10" v-for="(item, index) in list" :key="index">
			<view class="flex justify-start align-center text-cut">
				<block v-if="status == 1">
					<image @click="checkType(false, item)" v-if="item.selected" :src="baseUrl + '/static/selected.png'"
						mode="" style="width: 36rpx; height: 36rpx; min-width: 36rpx"></image>
					<image @click="checkType(true, item)" v-else :src="baseUrl + '/static/unselected.png'" mode=""
						style="width: 36rpx; height: 36rpx; min-width: 36rpx"></image>
				</block>

				<image :src="item.logo" mode="" class="round" style="
            width: 40rpx;
            min-width: 40rpx;
            height: 40rpx;
            margin-left: 20rpx;
          ">
				</image>
				<view class="margin-left-sm text-cut">
					{{ item.shopName }}
				</view>
			</view>
			<view class="flex justify-between align-center margin-top" v-for="(gItem, gIndex) in item.produces"
				:key="gIndex">
				<block v-if="status == 1">
					<image @click="changeType(false, gItem, item.id)" v-if="gItem.selected"
						:src="baseUrl + '/static/selected.png'" mode=""
						style="width: 36rpx; height: 36rpx; min-width: 36rpx"></image>
					<image @click="changeType(true, gItem, item.id)" v-else :src="baseUrl + '/static/unselected.png'"
						mode="" style="width: 36rpx; height: 36rpx; min-width: 36rpx"></image>
				</block>
				<block v-else>
					<image v-if="gItem.isShow" @click="changeEditType(false, gItem, item.id)"
						:src="baseUrl + '/static/selected.png'" mode=""
						style="width: 36rpx; height: 36rpx; min-width: 36rpx"></image>
					<image v-else @click="changeEditType(true, gItem, item.id)"
						:src="baseUrl + '/static/unselected.png'" mode=""
						style="width: 36rpx; height: 36rpx; min-width: 36rpx"></image>
				</block>
                     
				<image @click.stop="toPage2('/filePage/pages/goods-detail/goods-detail?id=' + gItem.productId)" :src="gItem.productImg" class="margin-left-xs" mode=""
					style="width: 200rpx; height: 200rpx; min-width: 200rpx"></image>
				<view class="f-grow1 margin-left-xs text-cut">
					<view class="text-cut">
						{{ gItem.productName }}
					</view>
					<view class="margin-top-sm text-sm text-999">
						{{ gItem.attributes }}
					</view>
					<view class="flex justify-between margin-top align-end">
						<view class="color">
							<text class="text-sm">¥ </text>
							<text class="text-xl text-bold">{{
                parseFloat(gItem.price / 100).toFixed(2)
              }}</text>
						</view>

						<yp-number-box @change="handChange" :value="gItem.buyNum" :min="1"
							:index="JSON.stringify(gItem)" />
					</view>
				</view>
			</view>
		</view>
		<!-- <uni-load-more :status="loading" /> -->
		<view class="" style="height: 98rpx"> </view>
		<view class="c-fooder flex justify-between align-center bg-white" v-if="status == 1">
			<view class="flex justify-start align-center" @click="cheackde">
				<view class="margin-right-sm"> 全选 </view>
				<image v-if="is_all" :src="baseUrl + '/static/selected.png'" mode=""
					style="width: 36rpx; height: 36rpx; min-width: 36rpx"></image>
				<image v-else :src="baseUrl + '/static/unselected.png'" mode=""
					style="width: 36rpx; height: 36rpx; min-width: 36rpx"></image>
			</view>
			<view class="flex justify-center align-center">
				<view class="text-15">
					<text>总计 </text>
					<text class="color">¥{{ parseFloat(total / 100).toFixed(2) }}</text>
				</view>
				<view @click="
            toPage(
              '/filePage/pages/confirm-order/confirm-order?type=1&cartIds=' +
                JSON.stringify(cartIds) +
                '&productNum=' +
                num +
                '&realAmount=' +
                total
            )
          " class="margin-left margin-right-sm text-white btn round padding-bottom-sm padding-top-sm padding-left padding-right">
					去结算({{ num }})
				</view>
			</view>
		</view>
		<view class="c-fooder flex justify-between align-center bg-white" v-if="status == 2">
			<!-- <view class="text-15" @click="clearCart">
				<text>清理</text>
			</view> -->
			<view class="flex justify-start align-center text-15" @click="cheackde">
				<view class="margin-right-sm"> 全选 </view>
				<image v-if="is_all" :src="baseUrl + '/static/selected.png'" mode=""
					style="width: 36rpx; height: 36rpx; min-width: 36rpx"></image>
				<image v-else :src="baseUrl + '/static/unselected.png'" mode=""
					style="width: 36rpx; height: 36rpx; min-width: 36rpx"></image>
			</view>
			<view @click="deleteById"
				class="margin-left margin-right-sm text-white btn round padding-bottom-sm padding-top-sm padding-left padding-right">
				删除
			</view>
		</view>
	</view>
</template>
<script>
	import ypNumberBox from "@/components/yp-number-box/yp-number-box.vue";
	// import BetterPull from '@/common/libs/BetterPull'
	export default {
		components: {
			ypNumberBox,
		},
		data() {
			return {
				baseUrl: this.$config.baseUrl,
				list: [],
				totalNum: 0,
				number: "",
				total: 0,
				num: 0,
				status: 1,
				cartIds: [], //选中的多商家商品
				shopId: "",
				reFreshStatus: "",
				isTrue: false,
				length: 0,
				is_all: false,
			};
		},
		watch: {
			//监听reFreshStatus,如果有修改就执行监听器
			reFreshStatus() {
				that.total = 0;
				that.num = 0;
				// console.log("页面已重新加载");
			},
		},
		onLoad() {},
		onShow() {
			this.getCartList();
		},
		methods: {
			cheackde() {
				if (this.list.length == 0) {
					return this.$util.msg("购物车暂无商品");
				}
				if (this.status == 1) {
					if (this.is_all) {
						this.is_all = false;
						for (let i in this.list) {
							this.list[i].selected = false;

							this.list[i].produces.forEach((val) => {
								val.selected = false;
								val.isShow = false;
							});
						}
					} else {
						this.is_all = true;
						for (let i in this.list) {
							this.list[i].selected = true;

							this.list[i].produces.forEach((val) => {
								val.selected = true;
								val.isShow = false;
							});
						}
					}
				} else {
					if (this.is_all) {
						this.is_all = false;
						for (let i in this.list) {
							this.list[i].selected = false;

							this.list[i].produces.forEach((val) => {
								val.selected = false;
								// this.$set(val, "selected", false);
								val.isShow = false;
							});
						}
					} else {
						this.is_all = true;
						for (let i in this.list) {
							this.list[i].selected = true;

							this.list[i].produces.forEach((val) => {
								val.selected = true;
								val.isShow = true;
							});
						}
					}
				}
				// console.log(this.list);
				this.totalPrice();
			},
			async getCartList() {
				const [err, res] = await this.$get(this.$api.car_getCar);
				if (res) {
					for (let i in res.data.shopResps) {
						// console.log(res.data.shopResps[i].produces)
						this.length += res.data.shopResps[i].produces.length;
					}
					// console.log(this.length)
					// console.log(res.data.shopResps)
					for (let i in res.data.shopResps) {
						this.$set(res.data.shopResps[i], "selected", false);
						res.data.shopResps[i].produces.forEach((val) => {
							this.$set(val, "selected", false);
							this.$set(val, "isShow", false);
						});
					}
					if (res.data.length != 0) {
						this.list = res.data.shopResps;
						this.totalNum = res.data.totalNum;
					} else {
						this.list = res.data;
						this.totalNum = 0;
					}

					// console.log(this.list)
				}
			},
			//获取数量
			async handChange(item) {
				if (this.isTrue) {
					uni.showLoading({
						title: "加载中",
						mask: true,
					});
					// console.log(item)
					const value = JSON.parse(item[0]);
					let num = item[1];
					let productId = value.productId;
					let shopId = value.shopId;
					let skuId = value.skuId;
					let id = value.id;
					// console.log(value.id)
					const datas = {
						num,
						productId,
						shopId,
						skuId,
					};
					const [err, rs] = await this.$post(this.$api.updateNum, datas);
					if (rs && rs.code == 200) {
						this.totalNum = 0;
						uni.hideLoading();
						let data = null;
						for (let i in this.list) {
							this.list[i].produces.forEach((val) => {
								if (val.id == id) {
									val.buyNum = Number(item[1]);
									// console.log(val)
								}
								this.totalNum += val.buyNum;
							});
							this.totalPrice();
						}
					}
				}

				this.length--;
				// console.log(this.length)
				if (this.length == 0) {
					this.isTrue = true;
				}

				// console.log(this.isTrue)
			},
			//计算总价
			totalPrice() {
				let list = this.list;
				let total = 0;
				let num = 0;
				let that = this;
				for (let i in list) {
					list[i].produces.forEach((val) => {
						if (val.selected) {
							// carts.shopId = val.shopId;
							// carts.cartIds = val.id;
							// cartIds.push(carts);
							total += val.buyNum * val.price;
							num += val.buyNum;
						}
					});
				}

				let cartIds = []

for(let i = 0; i< list.length;i++){
	let objs = {}
	let ary  =[]
	list[i].produces.forEach(e =>{
		if(e.selected){
			ary.push(e.id)
		}
	})
	// console.log('*********',ary.length)
	if(ary.length>0){
		objs.shopId = list[i].id
		objs.carts = ary
		cartIds.push(objs)
	}
	
}


					console.log(cartIds)
					this.is_all = true;
					// console.log( Array.from(new Set(cartIds)))
					this.cartIds = cartIds;
					this.total = total;
					this.num = num;
					for (let i in this.list) {
						if (!this.list[i].selected) {
							this.is_all = false;
						}
					}
				},
				//单个选中状态
				changeType(status, item, index) {
						// console.log(index)
						item.selected = status;
						const list = this.list;
						for (let i in list) {
							// if (list[i].id != index) {
							// 	// 不同店铺商品添加
							// 	list[i].selected = false;
							// 	list[i].produces.forEach((val) => {
							// 		val.selected = false;
							// 	});
							// } else {
							let state = list[i].produces.findIndex((val) => val.selected == false);
							// console.log(state)
							if (state > -1) {
								list[i].selected = false;
							} else {
								list[i].selected = true;
							}
							// }
						}

						this.totalPrice();
					},
					//一个店铺下选中状态
					checkType(status, item) {
						// console.log(status, item)
						const list = this.list;
						for (let i in list) {
							if (list[i].id == item.id) {
								list[i].selected = status;
								list[i].produces.forEach((val) => {
									val.selected = status;
								});
							}
							// else {
							// 	// 不同店铺商品添加
							// 	if (status) {
							// 		list[i].selected = !status;
							// 		list[i].produces.forEach((val) => {
							// 			val.selected = !status;
							// 		});
							// 	}
							// }
						}

						this.totalPrice();
					},

					//  //多商家一起结算
					// changeType(status, item, index) {
					// 	// console.log(index)
					// 	item.selected = status;
					// 	const list = this.list;
					// 	for (let i in list) {
					// 		if (list[i].id != index) {
					// 			// list[i].selected = false;
					// 			// list[i].produces.forEach((val) => {
					// 			// 	val.selected = false;
					// 			// });
					// 		} else {
					// 			let state = list[i].produces.findIndex(
					// 				(val) => val.selected == false
					// 			);
					// 			// console.log(state)
					// 			if (state > -1) {
					// 				list[i].selected = false;
					// 			} else {
					// 				list[i].selected = true;
					// 			}
					// 		}
					// 	}

					// 	this.totalPrice();
					// },
					// //一个店铺下选中状态
					// checkType(status, item) {
					// 	// console.log(status, item)
					// 	const list = this.list;
					// 	for (let i in list) {
					// 		if (list[i].id == item.id) {
					// 			list[i].selected = status;
					// 			list[i].produces.forEach((val) => {
					// 				val.selected = status;
					// 			});
					// 		}
					// 		else {
					// 			// if (status) {
					// 			// 	list[i].selected = !status;
					// 			// 	list[i].produces.forEach((val) => {
					// 			// 		val.selected = !status;
					// 			// 	});
					// 			// }
					// 		}
					// 	}

					// 	this.totalPrice();
					// },

					//管理 完成 切换
					editStatus(status) {
						this.status = status;
						this.cheackde();
					},
					//选中删除商品
					changeEditType(status, item) {
						// for (let i in this.list) {
						// 	this.list[i].produces.forEach((val) => {
						// 		val.isShow = false;
						// 	});
						// }
						item.isShow = status;
						console.log(this.list)
						this.is_all = true;
						for (let i in this.list) {
							this.list[i].produces.forEach((val) => {
								// val.isShow = false;
								if (!val.isShow) {
									this.is_all = false;
								}
							});

						}
					},
					//清理购物车
					clearCart() {
						// console.log(this.list)
						const {
							list
						} = this;
						if (list.length == 0) {
							return this.$util.msg("购物车暂无商品");
						}
						let that = this;
						uni.showModal({
							title: "提示",
							content: "你确定要清空购物车",
							success: function(res) {
								if (res.confirm) {
									that.$post(that.$api.clear).then((res) => {
										const [err, rs] = res;
										if (rs) {
											that.$util.msg(rs.message);
											that.getCartList();
											that.total = 0;
											that.num = 0;
											that.is_all = false
										}
									});
								} else if (res.cancel) {
									console.log("用户点击取消");
								}
							},
						});
					},

					//删除单个商品
					async deleteById() {
							if (this.is_all) {
								this.clearCart();
								return
							}
							const {
								list
							} = this;
							if (list.length == 0) {
								return this.$util.msg("购物车暂无商品");
							}
							let array = [];

							for (let i in this.list) {
								this.list[i].produces.forEach((val) => {
									let obj = {};
									if (val.isShow) {
										obj["productId"] = val.productId;
										obj["shopId"] = val.shopId;
										obj["skuId"] = val.skuId;
										array.push(obj);
									}
								});
							}
							// console.log(array)
							if (array.length == 0) {
								this.$util.msg("请选择要删除的商品");
							} else {
								const data  ={datas: JSON.stringify(array)}
								console.log(data)
								const [err, res] = await this.$get(this.$api.car_delete,data);
								console.log(array)
								if (res) {
									this.$util.msg(res.message);
									this.getCartList();
									this.total = 0;
									this.num = 0;
								}
							}
						},
						toPage2(url){
							this.$util.openNewPage(url);
						},
						toPage(url) {
							if (!this.num) {
							  return this.$util.msg("请选择要结算的商品");
							}
							this.total = 0;
							this.num = 0;
							this.$util.openNewPage(url);
							let selectProduct = []
							for (let i in this.list) {
								this.list[i].produces.forEach((val) => {
									if (val.selected) {
										selectProduct.push(val)
									}
								});
							}
							// console.log(url)

							// this.$util.openNewPage(url + '&selectProduct=' + JSON.stringify(this.selectProduct) + '&countPrice=' + this
							// 	.total + '&productNum=' + this.num)
						},
			},
		};
</script>
<style lang="scss" scoped>
	.c-fooder {
		position: fixed;
		left: 0;
		right: 0;
		height: 98rpx;
		bottom: 0;

		.btn {
			background: linear-gradient(135deg, #ff3c00, #ff5300);
		}
	}
</style>
